package com.ruoyi.common.utils.encry;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.util.Base64;

public class EncryPtionUtils {
    /**
     * 用来给apipost请求到的response进行解密
     *
     * @param bodyEncryPtion
     * @param keyBase64
     * @param ivBase64
     * @return
     */
    public static String getDecodeBodyForApiPost(String bodyEncryPtion, String keyBase64, String ivBase64) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        // 将十六进制密钥转换为 byte[]
        byte[] keyBytes = Base64.getDecoder().decode(keyBase64);
        String decryptedData = AESUtils.decryPtion(keyBytes, bodyEncryPtion, ivBase64);
        return decryptedData;
    }

    /**
     * 用于给apipost等接口调用工具提供固定密钥的body的加密内容，方便使用工具进行接口测试.
     * @param content 用户测试接口的时候， 提交的body参数
     * @param key
     * @param iv
     * @return 加密后内容
     * @throws Exception
     */
    public static String getBodyForApiPost(String content, byte[] key, byte[] iv) throws Exception{
        // 2. 使用AES加密数据
        String ivBase64 = Base64.getEncoder().encodeToString(iv);
        byte[] encryptedData = AESUtils.encryPtion(key, content.getBytes(StandardCharsets.UTF_8), ivBase64);
        String body = Base64.getEncoder().encodeToString(encryptedData);
        return body;
    }
}
